// 用户相关store
import type { UserLoginRequestDTO, UserLoginResponseDTO } from "@/api/sysAuth/sysAuthType";
import { defineStore } from "pinia";
import { ref } from "vue";
import type { RouteRecordRaw } from "vue-router";
import { mainContainerRoute, relationRoutes } from "@/router/routers";
import router from "@/router";
import type { SysUserAuthInfo } from "@/api/sysUser/sysUserType";
import { login, logout as apiLogout } from "@/api/sysAuth/sysAuth";
import { getUserAuthInfo } from "@/api/sysUser/sysUser";
import type { SysMenuVO } from "@/api/sysMenu/sysMenuType";
import SubContainer from "@/components/custom/SubContainer.vue";
import useTabStore from "./useTabStore";

export default defineStore("authStore", () => {
    /**
     * 用户认证信息
     */
    const authInfo = ref<UserLoginResponseDTO>()
    /**
     * 用户详细信息
     */
    const userInfo = ref<SysUserAuthInfo>()
    /**
     * 是否已经初始化过动态路由
     */
    let hasInitRoutes = ref(false)
    /**
     * 导入所有的vue文件
     */
    const modules = import.meta.glob("@/views/**/*.vue")

    /**
     * 登录，若成功则缓存用户信息
     * @param userInfo 
     */
    const loginAndCache = async (userInfo: UserLoginRequestDTO) => {
        authInfo.value = await login(userInfo)
    }

    /**
     * 退出登录
     */
    const logout = () => {
        apiLogout()
        localStorage.clear()
        location.reload()
    }

    /**
     * 获取用户信息，若成功则缓存用户信息
     */
    const initUserInfoAndCache = async () => {
        userInfo.value = await getUserAuthInfo()
    }

    /**
     * 初始化动态路由
     * @returns 
     */
    const initRoutes = () => {
        if (hasInitRoutes.value || !userInfo.value) {
            return
        }

        userInfo.value.menus.forEach(menu => addMenuToParent(menu, mainContainerRoute))

        router.addRoute(mainContainerRoute)

        // 缓存首页
        router.getRoutes().forEach(route => {
            if (route.meta.isHome) {
                useTabStore().indexRoute = route
            }
        })

        hasInitRoutes.value = true
    }

    /**
     * 将菜单添加到指定的父路由下，若菜单里有子菜单，则同时自动根据层级结构处理
     * @param menu 菜单
     * @param parentRoute  父路由
     */
    function addMenuToParent(menu: SysMenuVO, parentRoute: RouteRecordRaw) {
        if (!menu.path) {
            return
        }
        let route: RouteRecordRaw = {
            path: menu.path,
            name: menu.path,
            component: menu.component ? modules[`/src/views/${menu.component}.vue`] : SubContainer,
            meta: {
                title: menu.name,
                icon: menu.icon,
                isHome: menu.isHome
            }
        }

        if (!parentRoute.children) {
            parentRoute.children = []
        }

        parentRoute.children.push(route)

        // 加入关联路由
        if (menu.component && relationRoutes[menu.component]) {
            relationRoutes[menu.component].forEach(route => parentRoute.children?.push(route))
        }

        if (menu.children) {
            menu.children.forEach(menu => addMenuToParent(menu, route))
        }
    }

    return {
        authInfo,
        userInfo,
        hasInitRoutes,
        loginAndCache,
        logout,
        initUserInfoAndCache,
        initRoutes,
    }
}, {
    persist: {// 数据持久化配置
        omit: ["hasInitRoutes"] // 在持久化过程中需要忽略的字段
    },
})
